package io.shqyang.quicklib.base;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.IBundleManager;
import ohos.security.SystemPermission;

import static io.shqyang.quicklib.base.Constant.PERMISSION_REQUEST_CODE;

public abstract class QuickAbilitySlice extends AbilitySlice {

    protected abstract int layoutId();
    protected abstract void initComponent();
    protected abstract void initEvent();
    protected abstract void loadData(boolean isRefresh);
    
    private ToastDialog toastDialog;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(layoutId());
        initComponent();
        initEvent();
        loadData(true);
    }

    protected <T extends Component> T findComponent(int componentId) {
        T t = null;
        t = (T) findComponentById(componentId);
        return t;
    }

    protected <T extends ComponentContainer> T findContainer(int componentContainerId) {
        T t = null;
        t = (T) findComponentById(componentContainerId);
        return t;
    }


    public ToastDialog getToastDialog() {
        return toastDialog;
    }

    protected void toast(String text) {
        if (toastDialog == null) {
            toastDialog = new ToastDialog(getContext());
        }
        toastDialog.setText(text);
        toastDialog.show();
    }

    /**
     * request permissions
     * @param permissions   example: new String[] {SystemPermission.READ_USER_STORAGE}
     */
    protected void requestPermission(String[] permissions) {
        if (verifyCallingOrSelfPermission(permissions[0]) != IBundleManager.PERMISSION_GRANTED) {
            requestPermissionsFromUser(permissions, PERMISSION_REQUEST_CODE);
        }
    }
}
